package com.gitee.qdbp.general.mgr.controller.basedata.settings;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONException;
import com.gitee.qdbp.able.exception.ServiceException;
import com.gitee.qdbp.able.jdbc.ordering.OrderPaging;
import com.gitee.qdbp.able.jdbc.paging.PageList;
import com.gitee.qdbp.able.result.ResponseMessage;
import com.gitee.qdbp.able.result.ResultCode;
import com.gitee.qdbp.base.system.model.IAccount;
import com.gitee.qdbp.base.utils.SessionTools;
import com.gitee.qdbp.general.common.api.settings.model.SystemConfigCoreBean;
import com.gitee.qdbp.general.common.api.settings.model.SystemConfigCoreOptions;
import com.gitee.qdbp.general.common.api.settings.model.SystemConfigCoreUpdate;
import com.gitee.qdbp.general.common.api.settings.model.SystemConfigCoreWhere;
import com.gitee.qdbp.general.common.api.settings.params.UpdateCustomizeValueParams;
import com.gitee.qdbp.general.common.api.settings.service.ISystemConfigExecutor;
import com.gitee.qdbp.general.common.api.settings.service.ISystemConfigItemQueryer;
import com.gitee.qdbp.general.common.enums.ConfigDataType;
import com.gitee.qdbp.general.common.enums.ConfigScene;
import com.gitee.qdbp.general.common.enums.UsingState;
import com.gitee.qdbp.tools.utils.ConvertTools;
import com.gitee.qdbp.tools.utils.VerifyTools;
import libs.fastjson.com.alibaba.fastjson.JSON;

/**
 * 系统配置项信息控制器
 *
 * @author zhaohuihua
 * @version 170801
 */
@Controller
@RequestMapping("/actions/config-item/manager")
public class ConfigItemController {

    private static final ConfigScene SCENE_TYPE = ConfigScene.manager;
    private static final ConfigDataType DATA_TYPE = ConfigDataType.ITEM;

    @Autowired
    private ISystemConfigItemQueryer systemConfigItemQueryer;
    @Autowired
    private ISystemConfigExecutor systemConfigExecutor;

    @ResponseBody
    @RequestMapping("list")
    @RequiresPermissions("config-item:manager:query")
    public ResponseMessage list(SystemConfigCoreWhere model, OrderPaging paging, Boolean extra) {
        try {
            IAccount me = SessionTools.getLoginUser();
            model.setSceneType(SCENE_TYPE.name());
            model.setDataType(DATA_TYPE);
            PageList<?> pageList = systemConfigItemQueryer.list(SCENE_TYPE, me.getTenantCode(), model, paging);
            return new ResponseMessage(pageList);
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    @ResponseBody
    @RequestMapping("create")
    @RequiresPermissions("config-item:manager:create")
    public ResponseMessage create(SystemConfigCoreBean model, String valueType, String valueMetadata) {
        boolean develop = SessionTools.isDevelopMode();
        if (!develop) {
            return new ResponseMessage(ResultCode.FORBIDDEN);
        }

        try {
            resetBlankValue(model);
            parseOptions(model, valueType, valueMetadata);

            IAccount me = SessionTools.getLoginUser();
            model.setSceneType(SCENE_TYPE.name());
            model.setDataType(DATA_TYPE);
            String id = systemConfigExecutor.createCoreRecord(model, me);
            return new ResponseMessage(id);
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    @ResponseBody
    @RequestMapping("update")
    @RequiresPermissions("config-item:manager:update")
    public ResponseMessage updateCoreRecord(SystemConfigCoreBean model, String valueType, String valueMetadata) {
        boolean develop = SessionTools.isDevelopMode();
        if (!develop) {
            return new ResponseMessage(ResultCode.FORBIDDEN);
        }
        if (VerifyTools.isBlank(model.getId())) {
            return new ResponseMessage(ResultCode.PARAMETER_IS_REQUIRED);
        }

        try {
            IAccount me = SessionTools.getLoginUser();
            SystemConfigCoreUpdate ud = model.to(SystemConfigCoreUpdate.class);
            resetBlankValue(ud);
            parseOptions(ud, valueType, valueMetadata);
            ud.getWhere(true).setId(model.getId());
            ud.getWhere(true).setSceneType(SCENE_TYPE.name());
            ud.getWhere(true).setDataType(DATA_TYPE);
            systemConfigExecutor.updateCoreRecord(ud, me);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    @ResponseBody
    @RequestMapping("set-value")
    @RequiresPermissions("config-item:manager:set-value")
    public ResponseMessage updateCustomizeValue(UpdateCustomizeValueParams params) {
        if (VerifyTools.isBlank(params.getConfigKey())) {
            return new ResponseMessage(ResultCode.PARAMETER_IS_REQUIRED);
        }

        try {
            IAccount me = SessionTools.getLoginUser();
            params.setSceneType(SCENE_TYPE.name());
            params.setDataType(DATA_TYPE);
            systemConfigExecutor.updateCustomizeValue(params, me);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    private void resetBlankValue(SystemConfigCoreBean model) {
        if (model.getVisible() == null) {
            model.setVisible(false);
        }
        if (model.getEditable() == null) {
            model.setEditable(false);
        }
        if (model.getUsingState() == null) {
            model.setUsingState(UsingState.ENABLED);
        }
        if (model instanceof SystemConfigCoreUpdate) {
            SystemConfigCoreUpdate ud = (SystemConfigCoreUpdate) model;
            if (VerifyTools.isBlank(ud.getConfigValue())) {
                ud.setConfigValueToNull(true);
            }
            if (VerifyTools.isBlank(ud.getConfigText())) {
                ud.setConfigTextToNull(true);
            }
            if (VerifyTools.isBlank(ud.getConfigDesc())) {
                ud.setConfigDescToNull(true);
            }
        }
    }

    private void parseOptions(SystemConfigCoreBean model, String valueType, String valueMetadata)
            throws ServiceException {
        SystemConfigCoreOptions options = model.getOptions(true);
        if (VerifyTools.isBlank(valueType)) {
            options.setValueType("text");
        } else {
            options.setValueType(valueType);
        }

        if (VerifyTools.isBlank(valueMetadata)) {
            options.setValueMetadata(null);
        } else {
            try {
                options.setValueMetadata(JSON.parse(valueMetadata));
            } catch (JSONException e) {
                throw new ServiceException(ResultCode.PARAMETER_FORMAT_ERROR);
            }
        }
    }

    @ResponseBody
    @RequestMapping("delete")
    @RequiresPermissions("config-item:manager:delete")
    public ResponseMessage delete(String[] ids) {
        try {
            IAccount me = SessionTools.getLoginUser();
            systemConfigExecutor.deleteCoreRecordByIds(SCENE_TYPE.name(), ConvertTools.toList(ids), me);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }
}
